package com.txf.simple.utils;

import android.text.TextUtils;

import com.txf.simple.tools.JsonTools;
import com.txf.simple.tools.Logger;
import com.txf.simple.tools.StoreToadTools;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;


/**
 * 缓存工具
 * Created by chaosxing on 2016/3/27.
 */
public class CacheUtils {

    /**
     * 读取缓存
     *
     * @param key
     * @param classOfT
     * @param shelf_life 保质期
     * @return
     */
    public static <T> T getObject(String key, Class<T> classOfT, long shelf_life) {
        if (System.currentTimeMillis() - lastModified(key) > shelf_life) {
            return null;
        }
        return getObject(key, classOfT);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T> T getObject(String key, Class<T> classOfT) {
        String strCache = getString(key);
        if (!TextUtils.isEmpty(strCache)) {
            return JsonTools.parseObject(strCache, classOfT);
        } else {
            return null;
        }
    }

    /**
     * 读取缓存
     *
     * @param key
     * @param classOfT
     * @param shelf_life 保质期
     * @return
     */
    public static <T> List<T> getArray(String key, Class<T> classOfT, long shelf_life) {
        if (System.currentTimeMillis() - lastModified(key) > shelf_life) {
            return null;
        }
        return getArray(key, classOfT);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T> List<T> getArray(String key, Class<T> classOfT) {
        String strCache = getString(key);
        if (!TextUtils.isEmpty(strCache)) {
            return JsonTools.parseArray(strCache, classOfT);
        } else {
            return null;
        }
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public static String getString(String key) {
        try {
            return readUtf8(StoreToadTools.getInstance().getPagePath(), key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public static Object getObject(String key) {
        try {
            return readObject(StoreToadTools.getInstance().getPagePath(), key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取缓存
     *
     * @param key
     * @param shelf_life 有效期
     * @return
     */
    public static Object getObject(String key, long shelf_life) {
        if (System.currentTimeMillis() - lastModified(key) > shelf_life) {
            return null;
        }
        return readObject(StoreToadTools.getInstance().getPagePath(), key);
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param object
     * @return
     */
    public static boolean putString(String key, Object object) {
        try {
            writeObject(StoreToadTools.getInstance().getPagePath(), key, JsonTools.toJson(object));
            return true;
        } catch (Exception e) {
            Logger.e("缓存创建失败,key:" + key);
            return false;
        }
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param object
     * @return
     */
    public static boolean putObject(String key, Object object) {
        try {
            writeObject(StoreToadTools.getInstance().getPagePath(), key, object);
            return true;
        } catch (Exception e) {
            Logger.e("缓存创建失败,key:" + key);
            return false;
        }
    }

    /**
     * 上次修改日期
     *
     * @param key
     * @return
     */
    public static long lastModified(String key) {
        try {
            return new File(StoreToadTools.getInstance().getPagePath(), key).lastModified();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 读文件
     *
     * @param
     */
    public static String readUtf8(String path, String key) {
        File file = new File(path, key);
        if (!FileUtils.createNewFile(file)) {
            Logger.e("文件不存在，缓存" + key + "读取失败");
            return "";
        }

        BufferedSource bufferedSource = null;
        try {
            bufferedSource = Okio.buffer(Okio.source(file));
            return bufferedSource.readUtf8();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bufferedSource);
        }
        return "";
    }

    /**
     * 读文件
     *
     * @param
     */
    public static Object readObject(String path, String key) {
        File file = new File(path, key);
        if (!FileUtils.createNewFile(file)) {
            Logger.e("文件不存在，缓存" + key + "读取失败");
            return null;
        }

        BufferedSource bufferedSource = null;
        try {
            bufferedSource = Okio.buffer(Okio.source(file));
            return new ObjectInputStream(bufferedSource.inputStream()).readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bufferedSource);
        }
        return null;
    }

    /**
     * 写文件
     *
     * @param key
     * @param content
     * @return
     */
    public static boolean writeUtf8(String path, String key, String content) {
        File file = new File(path, key);
        if (!FileUtils.createNewFile(file)) {
            Logger.e("文件创建失败，缓存" + key + "储存失败");
            return false;
        }

        BufferedSink bufferedSink = null;
        try {
            bufferedSink = Okio.buffer(Okio.sink(file));
            bufferedSink.writeUtf8(content);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bufferedSink);
        }
        return false;
    }

    /**
     * 写文件
     *
     * @param key
     * @param content
     * @return
     */
    public static boolean writeObject(String path, String key, Object content) {
        File file = new File(path, key);
        if (!FileUtils.createNewFile(file)) {
            Logger.e("文件创建失败，缓存" + key + "储存失败");
            return false;
        }

        BufferedSink bufferedSink = null;
        try {
            bufferedSink = Okio.buffer(Okio.sink(file));
            new ObjectOutputStream(bufferedSink.outputStream()).writeObject(content);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bufferedSink);
        }
        return false;
    }

    /**
     * 关闭
     *
     * @param closeable
     */
    public static void closeQuietly(Closeable closeable) {

        if (closeable != null) {
            try {
                closeable.close();
            } catch (RuntimeException rethrown) {
                throw rethrown;
            } catch (Exception ignored) {
            }
        }
    }

}
